<script setup>
import { ref,watch,onMounted } from 'vue'
import { saveApi } from '@/api/user'
import { ElMessage,ElMessageBox } from 'element-plus'
import { queryAllApi } from '@/api/dept'
import { findAllApi } from '@/api/role'
import { peopleApi , deleteByIdApi,loginOutApi,deleteBatchApi} from '@/api/people'
import dayjs from 'dayjs'
onMounted(() => {
  seachDepts();
  seachRoles();
  onSubmit();
})
const seachDepts=async()=>{
  const result = await queryAllApi();
  depts.value = result.data;
}
const seachRoles=async()=>{
  const result = await findAllApi();
  roles.value = result.data;
}
const isStatus = ref(false);
//注册逻辑
const dialogVisible = ref(false)
const formRef = ref(null)
const registerform = ref({ id:'',name: '',phone: '',password: '',remark: '',deptId:'',roleId:'',status:1})
const depts = ref([])
const roles=ref([])
const titleName=ref('')
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6位', trigger: 'blur' }
    ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}
const onRegister = (title) => {
  dialogVisible.value = true
  titleName.value = title
  //清空registerform数据和校验
  formRef.value?.resetFields();
  registerform.value = {}
  isStatus.value=false
}
//注册提交按钮
const submitForm = async () => {
    try {
        await formRef.value.validate(); // 校验通过才会往下执行
      //发送请求
        const result = await saveApi(registerform.value);
        if (result.code == 200) {
        ElMessage.success(`${result.msg}！`)
        registerform.value = {}
        dialogVisible.value = false
        isStatus.value=false
        onSubmit()
        } else {
        ElMessage.error(result.msg)
      }
    }catch (error) {
        console.log(error)
    }
}
//搜索框
const formInline = ref({
  page: 1,
  size:10,
  name: '',
  deptId: '',
  startTime: '',
  endTime:'',
  date: []
})
watch(   
  () => formInline.value.date,
  (newValue) => {
    if (Array.isArray(newValue) && newValue.length === 2) {
      formInline.value.startTime = dayjs(newValue[0]).format('YYYY-MM-DD HH:mm:ss')
      formInline.value.endTime = dayjs(newValue[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    } else {
      formInline.value.startTime = ''
      formInline.value.endTime = ''
    }
  }
)
//清空搜索框
const onClear = () => {
  formInline.value.name = ''
  formInline.value.deptId = ''
  formInline.value.date=[]
}
//提交查询
const onSubmit = async() => {
  const result = await peopleApi(formInline.value);
  console.log(result)
  tableData.value = result.data.records
  if (result.data.records != null || result.data.records.length > 0) {
    currentPage4.value = Number(result.data.current)
    pageSize4.value = Number(result.data.size)
    totalall.value = Number(result.data.total)   
  } else {
    disabled.value = true
  }
}
//表格
const tableData = ref([]) // 空数组作为初始值
//修改
const handleClick = (row,title) => {
  dialogVisible.value = true
  titleName.value = title
  //清空registerform数据和校验
  formRef.value?.resetFields();
  registerform.value.id = row.id
  registerform.value.name = row.name
  registerform.value.phone = row.phone
  registerform.value.deptId = row.deptId
  registerform.value.roleId=row.roleId
  registerform.value.status = row.status==1?true:false
  isStatus.value = row.status == 1 ? true : false

}
//删除
const deleteUser = async(row) => {
  console.log(row)
  ElMessageBox.confirm(
    `确定要删除【${row.name}】这个用户吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    const result = await deleteByIdApi(row.id)
    if (result.code === 200) {
      ElMessage.success(result.msg)
      onSubmit();
    }
  })
}
//踢人下线
const loginOut = async (row) => {
  ElMessageBox.confirm(
    `确定要踢【${row.name}】下线吗？`,
    '确认踢下线',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    if (!row.boolLogin) {
      ElMessage.warning('该用户已下线！')
      return
    }
    const result = await loginOutApi(row.phone)
    if (result.code === 200) {
      ElMessage.success(result.msg)
      onSubmit()
    }
  })
}

//分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const background = ref(false)
const disabled = ref(false)
const totalall = ref(0);
const handleCurrentChange = (val) => {
  formInline.value.page = val
  onSubmit()
}
const handleSizeChange = (val) => {
  formInline.value.size = val
  onSubmit()

}
//批量删除
const multipleTable = ref(null);  // 用来拿表格的引用
const selectedRows = ref([]);     // 存储选中的行
const selectable = (row) => true
const handleSelectionChange = (val) => {
      selectedRows.value = val; // 监听选中变化
};
const onDelectNum = () => {
  if (selectedRows.value.length <= 0) {
    ElMessage.warning('请选择要删除的数据！')
  } else {
    ElMessageBox.confirm(
      `确定要删除这${selectedRows.value.length}个用户吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const numsId = selectedRows.value.map(item => item.id)
      const result = await deleteBatchApi(numsId);
      if (result.code === 200) {
        ElMessage.success(result.msg)
        onSubmit()
      }else  {
        ElMessage.error(result.msg)
      }
    })
  }
}
</script>
<template>
  <!-- 头部 -->
<div class="container">
  <h1>用户管理</h1>
  <el-button type="primary" @click="onRegister('注册')">+ 新增用户</el-button>
</div>
  <!-- 查询框 -->
<div class="container">
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="用户名">
      <el-input v-model="formInline.name" placeholder="请输入用户名" clearable />
    </el-form-item>
    <el-form-item label="部门选择">
  <el-select v-model="formInline.deptId" placeholder="请选择">
        <el-option 
        v-for="item in depts" 
        :key="item.id" 
        :label="item.name" 
        :value="item.id" />
    </el-select>
    </el-form-item>
    <el-form-item label="时间">
       <el-date-picker
        v-model="formInline.date"
        type="daterange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button type="success" @click="onClear">清空</el-button>
      <el-button type="danger" @click="onDelectNum">批量删除</el-button>
    </el-form-item>
  </el-form> 
</div>
  <!-- 表格 -->
<div class="container">
  <el-table :data="tableData" border ref="multipleTable" @selection-change="handleSelectionChange" style="width: 100%" row-key="id">
    <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
    <el-table-column type="index" label="序号" width="70" align="center" />
    <el-table-column prop="name" label="用户名" width="120" align="center"/>
    <el-table-column prop="phone" label="电话" width="150" align="center"/>
    <el-table-column prop="deptName" label="部门名称" width="150" align="center"/>
    <el-table-column prop="roleName" label="角色权限" width="150" align="center"/>
    <el-table-column prop="statusName" label="状态" width="120" align="center"/>
    <el-table-column label="是否登录" width="120" align="center">
    <template #default="{ row }">
      <span style="display: flex; align-items: center; justify-content: center; gap: 6px;">
        <span
          :style="{
            display: 'inline-block',
            width: '10px',
            height: '10px',
            borderRadius: '50%',
            backgroundColor: row.boolLogin ? 'green' : 'red'
          }"
        ></span>
      </span>
    </template>
  </el-table-column>
    <el-table-column prop="submitTime" label="创建时间" width="250" align="center"/>
    <el-table-column fixed="right" label="操作" min-width="240" align="center">
      <template #default="scoped">
        <div class="mb-4">
        <el-button  type="warning" size="small" @click="handleClick(scoped.row,'修改')">
          修改
        </el-button>
        <el-button  type="danger" size="small" @click="deleteUser(scoped.row)">删除</el-button>
        <el-button  type="primary" size="small" @click="loginOut(scoped.row)">踢人下线</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
</div>
<!-- 分页 -->
<div class="container">
    <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"  
      v-model:page-size="pageSize4"
      :page-sizes="[10, 20, 30, 40]"
      size="default"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalall"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</div>

<!-- 新增用户 -->
<el-dialog
    v-model="dialogVisible"
    :title="titleName"
    width="600"
  >
  <el-form :model="registerform" ref="formRef" :inline="true" class="demo-form-inline" :rules="rules" label-position="top">
    <el-form-item  label="姓名" class="black-label" prop="name">
      <el-input v-model="registerform.name"/>
    </el-form-item>
    <el-form-item  label="电话" class="black-label" prop="phone">
      <el-input v-model="registerform.phone"/>
    </el-form-item>
    <el-form-item  label="密码"  class="black-label" prop="password">
      <el-input type="password" v-model="registerform.password"/>
    </el-form-item>
    <el-form-item label="部门选择" prop="deptId">
    <el-select v-model="registerform.deptId" placeholder="请选择">
        <el-option 
        v-for="item in depts" 
        :key="item.id" 
        :label="item.name" 
        :value="item.id" />
    </el-select>
    </el-form-item>
    <el-form-item label="选择角色" prop="roleId">
    <el-select v-model="registerform.roleId" placeholder="请选择">
        <el-option 
        v-for="item in roles" 
        :key="item.id" 
        :label="item.name" 
        :value="item.id" />
    </el-select>
    </el-form-item>
    <el-form-item v-if="isStatus">
      <el-switch v-model="registerform.status" active-text="启用" inactive-text="禁用" />
    </el-form-item>
    <el-form-item label="备注" class="black-label" style="width: 100%">
    <el-input v-model="registerform.desc" type="textarea"/>
    </el-form-item>
  </el-form>  
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scope>
.container{
  margin: 15px 0px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>